import cgi
import os
import time

from google.appengine.api import users
from google.appengine.api import mail
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext.webapp import template


class OilPrice(db.Model):
			author = db.UserProperty()
			price = db.StringProperty()
			date = db.DateTimeProperty(auto_now_add=True)

class Inquiry(db.Model):
			author = db.StringProperty()
			author_email = db.EmailProperty()
			description = db.StringProperty(multiline=True)
			date = db.DateTimeProperty(auto_now_add=True)
			company = db.StringProperty()
			phone = db.StringProperty()
			is_open = db.BooleanProperty()			

class Admin(webapp.RequestHandler):
		def get(self):
		
			oil_price_query = OilPrice.all().order('-date')
			oil_prices = oil_price_query.fetch(1)
			
			inquiry_query = Inquiry.all().order('-date')
			inquiries = inquiry_query.fetch(30)

			if users.is_current_user_admin():
				admin_link = '| <a href="/admin/">Admin</a>'
			else:
				admin_link = ''

			if users.get_current_user():
				url = users.create_logout_url(self.request.uri)
				url_linktext = 'Logout'
			else:
				url = users.create_login_url(self.request.uri)
				url_linktext = 'Login'

			template_values = { 
				'page_title': "Admin Dashboard",
				'site_name': "Ace Oil, Inc.",
				'inquiries': inquiries,
				'oil_prices': oil_prices,
				'url': url,
				'url_linktext': url_linktext,
				'admin_link': admin_link
			}

			path = os.path.join(os.path.dirname(__file__), 'admin.html')
			self.response.out.write(template.render(path, template_values))

application = webapp.WSGIApplication(
                                     [('/admin/', Admin)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()